Popular Searches
Popular Course Categories
Popular Courses

XPath Interview Questions

XPath Interview Questions

Job Preparation

XPath Interview Questions

XPath (XML Path Language) is a locator strategy used in Selenium WebDriver to identify and interact with elements in an HTML or XML document. XPath is especially useful when elements do not have reliable IDs, names, or other unique attributes. It can locate elements using attributes, text, hierarchy, position, and relationships with other elements.

XPath is one of the most frequently discussed Selenium interview topics. Interviewers commonly ask about absolute and relative XPath, XPath functions, dynamic elements, axes, sibling relationships, text matching, XPath versus CSS Selector, and how to construct robust locators. :contentReference[oaicite:0]{index=0}

Course Resource: Selenium Training | Register for Course Demo


1. What is XPath?

XPath stands for XML Path Language. It is a query language used to navigate through elements and attributes in an XML or HTML document. In Selenium WebDriver, XPath is commonly used with the By.xpath() locator strategy to identify web elements.

WebElement username = driver.findElement(

    By.xpath("//input[@id='username']")

);

XPath is particularly useful when a web element does not have a suitable unique ID, name, or CSS selector. :contentReference[oaicite:1]{index=1}


2. Why is XPath Important in Selenium?

  • It can locate elements using attributes.
  • It can locate elements using visible text.
  • It can navigate through parent-child relationships.
  • It can navigate between sibling elements.
  • It can locate dynamic web elements.
  • It supports functions such as contains(), starts-with(), and normalize-space().
  • It supports XPath axes such as parent, ancestor, following-sibling, and preceding-sibling.
  • It is useful for complex DOM structures.
  • It can combine multiple conditions using and and or.


3. Basic XPath Syntax

The basic XPath syntax for locating an element using an attribute is:

//tagname[@attribute='value']

Example:

//input[@id='username']

In Selenium:

driver.findElement(

    By.xpath("//input[@id='username']")

).sendKeys("admin");


4. What are the Types of XPath?

There are two commonly discussed forms of XPath in Selenium:

  • Absolute XPath
  • Relative XPath

FeatureAbsolute XPathRelative XPath
Starting PointRoot of the documentCan start from any matching node
SyntaxStarts with /Usually starts with //
LengthUsually longUsually shorter
MaintainabilityMore fragileGenerally easier to maintain
Example/html/body/div/form/input//input[@id='username']


5. What is Absolute XPath?

An Absolute XPath starts from the root HTML element and specifies the complete path to the target element.

/html/body/div/main/section/form/div/input

It depends heavily on the exact DOM hierarchy. If an intermediate element is added, removed, or moved, the XPath may stop matching the intended element.

For this reason, long absolute XPath expressions are generally avoided in maintainable Selenium frameworks. :contentReference[oaicite:2]{index=2}


6. What is Relative XPath?

A Relative XPath does not require the complete path from the root. It commonly starts with // and identifies elements using attributes, text, relationships, or other conditions.

//input[@id='username']

Another example:

//button[@type='submit']

Relative XPath is generally preferred because it avoids unnecessary dependence on the complete page hierarchy. :contentReference[oaicite:3]{index=3}


7. What is the Difference Between / and // in XPath?

The single slash / represents a direct hierarchical step, while // can search for matching descendants at any depth from the current context.

/html/body/div

//input[@id='username']

//div[@id='login']//input

SymbolMeaningExample
/Direct child/path step//form/input
//Descendant search at any depth//form//input


8. How Do You Locate an Element Using an Attribute?

An element can be located by specifying its attribute and value.

//input[@id='username']

Examples:

//input[@name='email']

//button[@type='submit']

//input[@placeholder='Enter Username']

//div[@class='login-container']

Selenium example:

driver.findElement(

    By.xpath("//input[@name='email']")

).sendKeys("[email protected]");


9. How Do You Locate an Element Using Multiple Attributes?

Multiple attributes can be combined using the and operator.

//input[@type='text' and @name='username']

Another example:

//button[@type='submit' and @name='login']

This approach is useful when a single attribute is not unique.


10. How Do You Use the OR Condition in XPath?

The or operator can be used when an element may satisfy either of two conditions.

//input[@id='username' or @name='username']

This XPath matches an input whose ID is username or whose name is username.


11. What is the contains() Function in XPath?

The contains() function performs a partial match. It is particularly useful when an attribute contains a stable portion but its complete value changes dynamically.

//input[contains(@id,'username')]

For example, if the generated IDs are:

username_123

username_456

username_789

The following XPath can match them:

//input[contains(@id,'username')]

Interview Tip: contains() is frequently used for dynamic attributes. :contentReference[oaicite:4]{index=4}


12. What is starts-with() in XPath?

The starts-with() function matches an attribute whose value begins with a specified string.

//input[starts-with(@id,'user')]

For example:

user_123

user_456

user_789

The XPath:

//input[starts-with(@id,'user')]

can match these elements.


13. How Do You Locate an Element Using Text?

The text() function can be used when the visible text of an element is known.

//button[text()='Login']

Another example:

//h1[text()='Welcome']

Selenium example:

driver.findElement(

    By.xpath("//button[text()='Login']")

).click();


14. What is the Difference Between text() and contains(text(), ...)?

text() is commonly used for exact text matching, while contains(text(), ...) can be used for partial text matching.

//button[text()='Submit']

//button[contains(text(),'Submit')]

ExpressionPurpose
text()='Login'Exact text match
contains(text(),'Login')Partial text match


15. What is normalize-space()?

normalize-space() is useful when text contains extra spaces or inconsistent whitespace.

//button[normalize-space()='Login']

It is useful when the HTML contains formatting or whitespace that makes a simple text comparison unreliable.


16. How Do You Locate an Element Using Class?

An element can be located using its class attribute.

//input[@class='username-field']

However, if an element contains multiple classes, an exact class comparison may not always be appropriate.

<input class="form-control username-field active">

A partial match can be used when suitable:

//input[contains(@class,'username-field')]


17. How Do You Find a Child Element Using XPath?

A child element can be located using the parent-child relationship.

//div[@id='login']/input

This identifies an input that is a direct child of the matching div.

For descendants at any depth:

//div[@id='login']//input


18. How Do You Find a Parent Element?

The parent axis can be used to move from an element to its direct parent.

//input[@id='username']/parent::div

The parent shortcut can also be written as:

//input[@id='username']/..


19. What are XPath Axes?

XPath axes define relationships between the current node and other nodes in the DOM. They are especially useful when the target element itself does not have a stable attribute but a nearby element does. Common axes include parent, child, ancestor, descendant, following-sibling, preceding-sibling, following, preceding, and self. :contentReference[oaicite:5]{index=5}

AxisPurpose
parentSelects the direct parent
childSelects direct children
ancestorSelects ancestors
descendantSelects descendants
following-siblingSelects following siblings
preceding-siblingSelects preceding siblings
followingSelects nodes appearing later in the document
precedingSelects nodes appearing earlier in the document
selfSelects the current node


20. What is following-sibling in XPath?

following-sibling selects sibling elements that appear after the current element under the same parent.

//label[text()='Email']/following-sibling::input

This is useful when a label is stable but the associated input does not have a unique attribute. :contentReference[oaicite:6]{index=6}


21. What is preceding-sibling in XPath?

preceding-sibling selects sibling elements that appear before the current element.

//input[@id='email']/preceding-sibling::label

This can be useful for locating a label associated with a known input.


22. What is the difference between following-sibling and preceding-sibling?

AxisDirection
following-siblingMoves to siblings after the current element
preceding-siblingMoves to siblings before the current element

//label[text()='Username']/following-sibling::input

//input[@id='username']/preceding-sibling::label


23. What is the ancestor Axis?

The ancestor axis selects all ancestor elements of the current node.

//input[@id='username']/ancestor::form

This can be useful when the form itself has an important attribute but the input does not.


24. What is the descendant Axis?

The descendant axis selects elements located below the current node at any depth.

//div[@id='login']/descendant::input

It can locate input elements nested several levels inside the login container.


25. What is self in XPath?

The self axis refers to the current node.

//button[@id='login']/self::button

It is less frequently required in basic Selenium automation but is useful for understanding XPath navigation.


26. How Do You Handle Dynamic Web Elements Using XPath?

A dynamic web element is an element whose attributes may change between executions or page loads. XPath can handle such elements by using stable portions of attributes, text, multiple conditions, or relationships with nearby elements.

Common techniques include:

  • contains()
  • starts-with()
  • normalize-space()
  • text()
  • and
  • or
  • XPath axes
  • Parent-child relationships
  • Sibling relationships

These approaches are commonly discussed in Selenium interview preparation. :contentReference[oaicite:7]{index=7}


27. Example of Dynamic XPath

Suppose an element has changing IDs:

id="user_1001"

id="user_1002"

id="user_1003"

A partial XPath can be:

//input[contains(@id,'user_')]

If the stable portion is at the beginning:

//input[starts-with(@id,'user_')]


28. How Do You Handle Dynamic Text?

When the complete text changes but a stable portion remains, contains() can be used.

//div[contains(text(),'Order')]

For example, this may match text such as:

Order #1001

Order #1002

Order #1003


29. How Do You Use Multiple Conditions in XPath?

Multiple conditions can make a locator more specific.

//input[@type='text' and @name='username' and @required='true']

Another example:

//button[contains(@class,'login') and @type='submit']


30. What is XPath Indexing?

XPath supports positional indexes for selecting elements from a group of matching elements.

(//input[@type='text'])[1]

(//input[@type='text'])[2]

(//button)[3]

Indexes can be useful in controlled DOM structures, but relying heavily on positional indexes can make locators fragile when page structure changes.


31. How Do You Select the First Matching Element?

The first matching element can be selected using position 1.

(//input[@type='text'])[1]


32. How Do You Select the Last Matching Element?

The last() function can select the last matching element.

//input[@type='text'][last()]

Another example:

//tr[last()]


33. What is position() in XPath?

The position() function can be used to select elements based on their position in a node set.

//li[position()=1]

//li[position()=2]

//li[position()<3]

This can be useful when working with lists or repeated elements.


34. How Do You Find a Specific Table Row?

XPath can locate a table row using text contained within one of its cells.

//tr[td[normalize-space()='Laptop']]

This identifies a row containing a cell whose normalized text is Laptop.


35. How Do You Find a Cell Relative to Another Cell?

XPath axes can be used to navigate between table cells.

//td[normalize-space()='Laptop']/following-sibling::td[1]

This can locate the next cell in the same row.


36. How Do You Find the Price of a Product in a Table?

Suppose a table contains:

<tr>

    <td>Laptop</td>

    <td>Electronics</td>

    <td>₹50,000</td>

</tr>

The price can be located using:

//td[normalize-space()='Laptop']/following-sibling::td[2]


37. How Do You Find a Checkbox Relative to a Label?

If the label is stable, an associated checkbox can sometimes be located using a relationship in the DOM.

//label[normalize-space()='Remember Me']/following-sibling::input[@type='checkbox']

The exact XPath depends on the page structure, so the DOM relationship should always be verified before using the locator.


38. How Do You Find a Button Based on Its Text?

//button[normalize-space()='Submit']

For partial text:

//button[contains(normalize-space(),'Submit')]


39. What is the Difference Between contains() and starts-with()?

FunctionPurposeExample
contains()Matches a value containing text anywhere//input[contains(@id,'user')]
starts-with()Matches a value beginning with text//input[starts-with(@id,'user')]


40. What is the Difference Between XPath and CSS Selector?

FeatureXPathCSS Selector
SyntaxMore expressiveUsually shorter
Text MatchingSupports text-based expressionsNo direct text() equivalent
DOM TraversalCan navigate in multiple directionsPrimarily follows CSS selector relationships
Dynamic ElementsContains, starts-with, axes, etc.Attribute and structural selectors
ReadabilityCan become complexOften concise for simple selectors

XPath is particularly useful when text matching or relationship-based traversal is required. CSS selectors are often concise for straightforward IDs, classes, attributes, and structural relationships. :contentReference[oaicite:8]{index=8}


41. Is XPath Always Better Than CSS Selector?

No locator strategy is universally best. The appropriate choice depends on the application DOM and the stability and readability of the locator.

CSS selectors are often convenient for simple stable attributes, while XPath is useful when text matching or navigation through DOM relationships is required. Modern browser performance differences should not be treated as the only deciding factor; locator stability and maintainability are important considerations. :contentReference[oaicite:9]{index=9}


42. What Makes a Good XPath?

A good XPath should be:

  • Unique or sufficiently specific.
  • Readable.
  • Stable across expected UI changes.
  • Based on meaningful attributes or relationships.
  • Short enough to maintain.
  • Independent of unnecessary DOM structure.

Avoid long absolute paths and selectors that depend unnecessarily on layout or changing styling classes. :contentReference[oaicite:10]{index=10}


43. What is a Bad XPath?

Examples of fragile XPath include:

/html/body/div[2]/div[1]/section/div[3]/form/input[1]

Another fragile approach is excessive reliance on indexes:

(//button)[7]

These expressions can break when the DOM structure or element order changes.


44. How Do You Verify an XPath in Chrome DevTools?

XPath expressions can be tested in the browser's developer tools console using the $x() function.

$x("//input[@id='username']")

For example:

$x("//button[normalize-space()='Login']")

The result can be inspected to confirm whether the locator identifies the intended element.


45. How Do You Check Whether an XPath Is Unique?

In Chrome DevTools, use:

$x("//input[@id='username']")

If the expression returns more than one element, refine the XPath using additional stable conditions.

//input[@type='text' and @id='username']


46. What is the Difference Between findElement() and findElements() with XPath?

MethodReturn TypeBehavior
findElement()WebElementReturns the first matching element and throws an exception if none is found
findElements()List<WebElement>Returns all matching elements; an empty list is returned if none are found

Examples:

WebElement loginButton = driver.findElement(

    By.xpath("//button[@type='submit']")

);

 

List<WebElement> buttons = driver.findElements(

    By.xpath("//button")

);


47. How Do You Find All Links Using XPath?

Anchor elements can be located using:

//a

Selenium example:

List<WebElement> links = driver.findElements(

    By.xpath("//a")

);

 

System.out.println("Total links: " + links.size());


48. How Do You Find All Input Fields Using XPath?

//input

Specific input types can also be selected:

//input[@type='text']

//input[@type='password']

//input[@type='checkbox']

//input[@type='radio']


49. How Do You Find All Buttons Using XPath?

//button

Buttons with specific attributes can be located using:

//button[@type='submit']

//button[contains(@class,'login')]


50. How Do You Locate an Element Using Two Possible Attributes?

The or operator can be used:

//input[@id='email' or @name='email']

This can be useful when different versions of an application use different stable attributes.


51. How Do You Locate an Element Based on Parent and Child Relationships?

//div[@id='login']/input[@name='username']

For any descendant:

//div[@id='login']//input[@name='username']


52. How Do You Locate an Element Relative to Another Element?

This is one of the most useful interview scenarios involving XPath axes.

//label[normalize-space()='Username']/following-sibling::input

Another example:

//span[normalize-space()='Price']/following-sibling::span

Relationship-based XPath is especially useful when the target element lacks a reliable unique attribute. :contentReference[oaicite:11]{index=11}


53. How Do You Handle an Element with Multiple Classes?

Suppose the element is:

<button class="btn primary submit-button">Submit</button>

Instead of assuming the complete class string is stable, a partial class match can be used:

//button[contains(@class,'submit-button')]


54. How Do You Handle Dynamic IDs?

If an ID changes but contains a stable portion:

//input[contains(@id,'username')]

If the ID always starts with a stable prefix:

//input[starts-with(@id,'username_')]


55. How Do You Locate an Element by Partial Text?

//a[contains(text(),'Learn')]

Another example:

//button[contains(normalize-space(),'Continue')]


56. What is the Difference Between Attribute and Text-Based XPath?

TypeExample
Attribute-based//input[@id='username']
Text-based//button[text()='Login']
Partial attribute//input[contains(@id,'user')]
Partial text//button[contains(text(),'Login')]


57. What is XPath Chaining?

XPath chaining means building a locator by navigating through multiple relationships.

//div[@id='login']//form//input[@name='username']

Although chaining can be useful, avoid making the locator unnecessarily long. Use the smallest stable path that uniquely identifies the intended element.


58. How Do You Locate the Nth Element?

Use an index or position condition.

(//button[@type='button'])[3]

Using position:

//button[@type='button'][position()=3]

Use indexes carefully because DOM ordering can change.


59. How Do You Select the Last Table Row?

//table//tr[last()]

If a more specific table locator exists, it is preferable to scope the XPath to that table.


60. How Do You Select the First Three Elements?

//li[position() <= 3]

This selects the first three matching list items.


61. How Do You Locate an Element Using a Parent Attribute?

Suppose the input itself has no useful attribute but its parent does:

//div[@id='username-container']//input

This locates an input descendant within the known container.


62. How Do You Find a Parent Based on a Child?

//input[@id='username']/parent::div

Or:

//input[@id='username']/..


63. How Do You Find an Ancestor Based on a Child?

//input[@id='username']/ancestor::form

This can locate the form containing the username input.


64. How Do You Locate an Element Using following-sibling?

//label[normalize-space()='Password']/following-sibling::input

If multiple following siblings exist, an additional condition can be applied:

//label[normalize-space()='Password']/following-sibling::input[1]


65. How Do You Locate an Element Using preceding-sibling?

//input[@id='password']/preceding-sibling::label

This navigates from the input to a preceding sibling label.


66. What are Common XPath Functions Asked in Interviews?

FunctionPurposeExample
contains()Partial match//input[contains(@id,'user')]
starts-with()Prefix match//input[starts-with(@id,'user')]
text()Text matching//button[text()='Login']
normalize-space()Whitespace normalization//button[normalize-space()='Login']
last()Last matching node//tr[last()]
position()Position-based selection//li[position()=2]


67. What are Common XPath Axes Asked in Interviews?

  • parent: Selects the direct parent.
  • child: Selects direct children.
  • ancestor: Selects ancestor elements.
  • descendant: Selects descendant elements.
  • following-sibling: Selects following siblings.
  • preceding-sibling: Selects preceding siblings.
  • following: Selects nodes later in document order.
  • preceding: Selects nodes earlier in document order.
  • self: Selects the current node.


68. What is the Best Approach for Dynamic XPath?

A practical approach is to identify which portion of the element is stable and construct the locator around that stable information.

Dynamic ID:

user_12345

 

Stable portion:

user_

 

XPath:

 //input[starts-with(@id,'user_')]

For a dynamic text value:

//div[contains(text(),'Order')]

For a relationship-based locator:

//label[normalize-space()='Email']/following-sibling::input


69. How Do You Make XPath More Maintainable?

  • Prefer stable attributes.
  • Prefer unique IDs when they are stable and meaningful.
  • Use dedicated test attributes when available, such as data-testid.
  • Avoid unnecessary absolute paths.
  • Avoid unnecessary index-based locators.
  • Use contains() only when partial matching is actually needed.
  • Use normalize-space() for text with inconsistent whitespace.
  • Use axes when relationships provide more stable identification.
  • Keep XPath expressions readable.
  • Verify that the locator identifies the intended element.

Interview guidance increasingly emphasizes locator stability and avoiding absolute paths, arbitrary indexes, and styling classes that change frequently. :contentReference[oaicite:12]{index=12}


70. Practical Selenium XPath Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class XPathExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(

            By.xpath("//input[@id='username']")

        ).sendKeys("admin");

 

        driver.findElement(

            By.xpath("//input[@id='password']")

        ).sendKeys("admin123");

 

        driver.findElement(

            By.xpath("//button[normalize-space()='Login']")

        ).click();

 

        driver.quit();

    }

}


71. Practical Dynamic XPath Example

WebElement username = driver.findElement(

    By.xpath("//input[contains(@id,'username')]")

);

 

WebElement submit = driver.findElement(

    By.xpath("//button[contains(@class,'submit')]")

);

 

WebElement email = driver.findElement(

    By.xpath("//label[normalize-space()='Email']/following-sibling::input")

);


72. XPath Interview Scenario: Login Page

Suppose a login page contains:

<input id="username" name="username" type="text">

<input id="password" name="password" type="password">

<button type="submit">Login</button>

Possible XPath expressions are:

//input[@id='username']

//input[@name='password']

//button[@type='submit']

//button[text()='Login']

//button[normalize-space()='Login']


73. XPath Interview Scenario: Dynamic Button

Suppose the button has a dynamic class:

<button class="btn-submit-12345">Submit Order</button>

Possible XPath:

//button[contains(@class,'btn-submit')]

Or using text:

//button[contains(normalize-space(),'Submit Order')]


74. XPath Interview Scenario: Table

Suppose the table contains product names and prices:

<tr>

    <td>Laptop</td>

    <td>Electronics</td>

    <td>50000</td>

</tr>

To find the price:

//td[normalize-space()='Laptop']/following-sibling::td[2]

This type of relationship-based XPath is useful in dynamic tables where the target cell does not have a unique attribute.


75. XPath Interview Scenario: Checkbox

<label>Remember Me</label>

<input type="checkbox" id="remember">

Possible XPath:

//input[@id='remember']

Or, if the relationship is stable:

//label[normalize-space()='Remember Me']/following-sibling::input[@type='checkbox']


76. Common XPath Interview Questions

Question 1: What is XPath?

XPath is a query language used to navigate and identify nodes in XML and HTML documents. Selenium uses XPath as one of its locator strategies.

Question 2: What is the difference between absolute and relative XPath?

Absolute XPath specifies the complete path from the root element, while relative XPath identifies an element using a relative expression such as attributes, text, or relationships. Relative XPath is generally preferred for maintainability. :contentReference[oaicite:13]{index=13}

Question 3: What is the difference between / and //?

/ represents a direct path step, while // searches descendants at any depth from the current context.

Question 4: What is contains()?

contains() performs a partial match and is frequently useful for dynamic attribute values.

Question 5: What is starts-with()?

starts-with() matches values beginning with a specified string.

Question 6: How do you locate an element by text?

Use text(), for example //button[text()='Login'].

Question 7: What is normalize-space()?

normalize-space() normalizes whitespace and can make text-based XPath expressions more robust when spacing varies.

Question 8: What are XPath axes?

XPath axes define relationships between the context node and other nodes, such as parent, ancestor, child, following-sibling, and preceding-sibling.

Question 9: How do you locate a sibling element?

Use following-sibling or preceding-sibling depending on the required direction.

Question 10: How do you handle dynamic elements?

Use stable attributes, contains(), starts-with(), normalize-space(), multiple conditions, or relationship-based XPath.

Question 11: How do you locate the last element?

Use last(), for example //tr[last()].

Question 12: How do you locate the second element?

Use an index or position, for example (//button)[2] or //button[position()=2].

Question 13: Can XPath locate an element using text?

Yes. XPath supports text-based expressions such as //button[text()='Login'].

Question 14: Can XPath navigate to a parent?

Yes. The parent axis or /.. can be used.

Question 15: Can XPath navigate to an ancestor?

Yes. The ancestor axis can be used.

Question 16: Can XPath navigate to a sibling?

Yes. following-sibling and preceding-sibling can be used.

Question 17: What is a dynamic web element?

It is an element whose attributes or other identifying properties can change between executions or page states.

Question 18: How do you write XPath for a dynamic ID?

Use a stable portion with contains() or starts-with().

Question 19: What is the difference between XPath and CSS Selector?

XPath provides powerful text matching and relationship-based DOM traversal, while CSS selectors are often concise for straightforward attribute and structural selections. :contentReference[oaicite:14]{index=14}

Question 20: Is absolute XPath recommended?

Long absolute XPath is generally avoided because it is highly dependent on the DOM hierarchy and can become fragile when the page structure changes.

Question 21: How do you verify XPath?

In browser developer tools, XPath can be tested using the $x() function.

Question 22: What is the use of normalize-space()?

It helps handle inconsistent whitespace in text nodes.

Question 23: How do you locate an element using multiple conditions?

Use logical operators such as and and or.

Question 24: What is the use of following-sibling?

It identifies sibling elements appearing after the current element under the same parent.

Question 25: What is the use of preceding-sibling?

It identifies sibling elements appearing before the current element under the same parent.


77. Advanced XPath Interview Questions

1. How would you locate an input field when only its label is known?

//label[normalize-space()='Email']/following-sibling::input

2. How would you locate a product price using the product name?

//td[normalize-space()='Laptop']/following-sibling::td[2]

3. How would you handle a dynamic ID?

//input[contains(@id,'user')]

4. How would you locate an element whose ID begins with a known prefix?

//input[starts-with(@id,'user_')]

5. How would you find the last row of a table?

//table//tr[last()]

6. How would you find the parent of an element?

//input[@id='username']/parent::div

7. How would you find an ancestor form?

//input[@id='username']/ancestor::form

8. How would you find the first matching button?

(//button)[1]

9. How would you find an element with partial visible text?

//button[contains(text(),'Submit')]

10. How would you handle extra whitespace in visible text?

//button[normalize-space()='Submit Order']


78. XPath Mistakes to Avoid in Interviews

  • Do not claim that XPath is always better than CSS.
  • Do not rely unnecessarily on long absolute XPath.
  • Do not use arbitrary indexes when a stable attribute exists.
  • Do not assume a copied browser XPath is automatically maintainable.
  • Do not use unstable CSS classes merely because they are available.
  • Do not create extremely long XPath expressions without a reason.
  • Do not forget to verify uniqueness.
  • Do not ignore DOM relationships when the target has no stable attribute.
  • Do not confuse following-sibling with preceding-sibling.
  • Do not confuse direct child relationships with descendant searches.


79. XPath Quick Revision Table

ConceptExample
Attribute//input[@id='username']
Text//button[text()='Login']
Contains//input[contains(@id,'user')]
Starts With//input[starts-with(@id,'user_')]
Normalize Space//button[normalize-space()='Login']
Parent//input[@id='username']/parent::div
Ancestor//input[@id='username']/ancestor::form
Child//div[@id='login']/child::input
Descendant//div[@id='login']/descendant::input
Following Sibling//label/following-sibling::input
Preceding Sibling//input/preceding-sibling::label
First(//button)[1]
Last//button[last()]
Position//button[position()=2]
AND//input[@type='text' and @name='user']
OR//input[@id='user' or @name='user']


80. XPath Interview Preparation Flow

XPath Basics

      |

      v

Absolute vs Relative XPath

      |

      v

Attributes and Text

      |

      v

contains() / starts-with()

      |

      v

normalize-space()

      |

      v

AND / OR Conditions

      |

      v

XPath Index and Position

      |

      v

XPath Axes

      |

      v

Dynamic Elements

      |

      v

Tables and Complex DOM

      |

      v

XPath vs CSS

      |

      v

Selenium Practical Coding

      |

      v

Interview Scenarios


81. Practical Interview Exercise

Consider the following HTML:

<div class="login">

    <label>Username</label>

    <input id="user_123" type="text">

    <label>Password</label>

    <input id="pass_456" type="password">

    <button class="btn-login">Login</button>

</div>

Possible XPath expressions:

//input[starts-with(@id,'user_')]

 

//input[starts-with(@id,'pass_')]

 

//label[normalize-space()='Username']/following-sibling::input

 

//label[normalize-space()='Password']/following-sibling::input

 

//button[contains(@class,'btn-login')]

 

//button[normalize-space()='Login']


82. Selenium Interview Coding Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class XPathInterviewExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        driver.findElement(

            By.xpath("//input[contains(@id,'username')]")

        ).sendKeys("admin");

 

        driver.findElement(

            By.xpath("//input[contains(@id,'password')]")

        ).sendKeys("admin123");

 

        driver.findElement(

            By.xpath("//button[normalize-space()='Login']")

        ).click();

 

        driver.quit();

    }

}


83. Real-World XPath Framework Usage

Web Application

      |

      v

DOM Inspection

      |

      v

Identify Stable Attribute / Text

      |

      +-------------------+

      |                   |

      v                   v

Simple Locator       Complex Relationship

      |                   |

      v                   v

CSS / XPath          XPath Axes

      |                   |

      +---------+---------+

                |

                v

Reusable Locator

                |

                v

Page Object Class

                |

                v

TestNG Test

                |

                v

Test Report


84. Final Summary

XPath is an important Selenium WebDriver locator strategy used to identify elements based on attributes, text, hierarchy, position, and relationships. It is especially useful for complex DOM structures and dynamic web elements.

For interviews, candidates should understand the difference between absolute and relative XPath, attribute-based XPath, text-based XPath, contains(), starts-with(), normalize-space(), indexes, position(), and XPath axes such as parent, ancestor, child, descendant, following-sibling, and preceding-sibling.

Strong XPath knowledge also requires practical understanding of dynamic elements, tables, form controls, Selenium By.xpath(), XPath validation in browser developer tools, and the differences between XPath and CSS selectors. Current Selenium interview resources commonly include these locator and XPath topics alongside waits, element handling, TestNG, and framework design. :contentReference[oaicite:15]{index=15}


85. Course Resources

Learn more about Selenium WebDriver, automation testing, XPath, TestNG, and framework development:

Final Takeaway: In Selenium interviews, XPath questions usually test both syntax and practical DOM reasoning. Focus on writing short, stable, readable locators, understanding XPath functions and axes, handling dynamic elements, and explaining why a particular locator is appropriate for the page structure.

whatsapp